package chamster.utils;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

public class Graph<NodeType> {
	private final Set<Tuple<NodeType, NodeType>> connections; 
	
	public Graph(Set<Tuple<NodeType, NodeType>> connections) {
		this.connections = connections;
	}
	
	
	public NodeType findOne(Function1<NodeType, Boolean> filter) {
		for(NodeType node : this.getNodes()) {
			if(filter.apply(node)) {
				return node;
			}
		}
		return null;
	}
	
	public Collection<NodeType> getNodes() {
		Set<NodeType> nodes = new HashSet<NodeType>();
		for(Tuple<NodeType, NodeType> tuple : this.connections) {
			nodes.add(tuple.getValue1());
			nodes.add(tuple.getValue2());
		}
		return nodes;
	}
	
	public boolean connected(NodeType node1, NodeType node2) {
		boolean connected = this.connections.contains(new Tuple<NodeType, NodeType>(node1, node2))
				|| this.connections.contains(new Tuple<NodeType, NodeType>(node2, node1));
		return connected;
	}
	
	public Set<NodeType> getConnectedNodes(NodeType node) {
		Set<NodeType> connectedNodes = new HashSet<NodeType>();
		for(Tuple<NodeType, NodeType> connection : this.connections) {
			if(connection.getValue1().equals(node)) {
				connectedNodes.add(connection.getValue2());
			}
			if(connection.getValue2().equals(node)) {
				connectedNodes.add(connection.getValue1());
			}
		}
		return connectedNodes;
	}
}
